<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :title="parameter.title"
    :destroy-on-close="true"
    :width="parameter.width"
    :top="parameter.top"
    draggable
  >
    <ProFrom ref="proFormRef" :items-options="itemsOptions" :form-options="_options" :model="model" />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="butLoading" @click="handleSubmit">确认</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ImageUploadDialog">
import ProFrom from '@/components/ProForm/index.vue'
export interface DialogProps {
  title: string // 标题
  width?: number // 弹框宽度
  top?: string // 离顶部距离
  type?: File.FileUploadType // 弹框类型 默认file-upload-s3：s3服务器上传文件
  getTableList?: () => void // 获取表格数据的Api
}
// 表单的数据
const model = ref<Record<string, any>>({ file: undefined })
// dialog状态
const dialogVisible = ref(false)
const butLoading = ref(false)
// 父组件传过来的参数
const parameter = ref<DialogProps>({
  title: '',
  width: 500,
  top: '10vh',
  type: 'file-upload-s3'
})
const _options: ComputedRef<ProForm.FormOptions> = computed(() => {
  return {
    labelWidth: 120,
    hasFooter: false,
    disabled: false
  }
})
let itemsOptions = reactive<ProForm.ItemsOptions[]>([])
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '上传',
      prop: 'file',
      rules: [{ required: true, message: '文件不能为空', trigger: 'change' }],
      compOptions: {
        elTagName: parameter.value.type
      }
    }
  ]
}

const proFormRef = ref<InstanceType<typeof ProFrom> | null>(null)

// 表单提交校验
const handleSubmit = () => {
  const formEl = proFormRef.value?.proFormRef
  console.log(proFormRef.value?.formModel)
  butLoading.value = true
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      parameter.value.getTableList && parameter.value.getTableList()
      dialogVisible.value = false
    }
    butLoading.value = false
  })
}

// 取消按钮，重置表单，关闭弹框
const handleCancel = () => {
  butLoading.value = false
  dialogVisible.value = false
}

// 接收父组件参数
const openDialog = (params: DialogProps) => {
  parameter.value = { ...parameter.value, ...params }
  butLoading.value = false
  setItemsOptions()
  dialogVisible.value = true
}

defineExpose({
  openDialog
})
</script>
